from apps.work.filters import WorkFilter, OrderFilter, KqExtendInfoFilter, KqMaintainInfoFilter, KqPriceInfoFilter, \
    KqPumpsFilter, KqAllProjectsFilter,DeptFilter,RoleFilter,UserProfileFilter
from rest_framework.request import Request
from apps.vadmin.op_drf.response import SuccessResponse, ErrorResponse
from apps.work.models import All_Kq_Infos, All_Kq_Orders, Kq_Extend_infos, Kq_Maintain_infos, Kq_Price_infos, \
    Kq_All_Pumps, Kq_All_Projects,Comp_Dept,Comp_Role,Comp_User

from apps.work.serializers import WorkSerializer, WorkCreateUpdateSerializer, ExportWorkSerializer
from apps.work.serializers import OrderSerializer, OrderCreateUpdateSerializer, ExportOrderSerializer
from apps.work.serializers import KqExtendInfoSerializer, KqExtendInfoCreateUpdateSerializer
from apps.work.serializers import KqMaintainSerializer, KqMaintainCreateUpdateSerializer, ExportMaintainSerializer
from apps.work.serializers import KqPriceSerializer, KqPriceCreateUpdateSerializer
from apps.work.serializers import KqPumpsSerializer, KqPumpsCreateUpdateSerializer, ExportKqPumpsSerializer
from apps.work.serializers import KqAllProjectsSerializer, KqAllProjectCreateUpdateSerializer
from apps.work.serializers import WorkDeptSerializer,WorkDeptCreateUpdateSerializer,WorkDeptTreeSerializer
from apps.work.serializers import RoleCreateUpdateSerializer,RoleSerializer,ExportRoleSerializer
from apps.work.serializers import UserProfileSerializer,UserProfileCreateUpdateSerializer
from apps.vadmin.op_drf.viewsets import CustomModelViewSet

class WorkUserModelViewSet(CustomModelViewSet):
    """
    用户管理 的CRUD视图
    """
    queryset = Comp_User.objects.all()
    serializer_class = UserProfileSerializer
    create_serializer_class = UserProfileCreateUpdateSerializer
    update_serializer_class = UserProfileCreateUpdateSerializer
    filter_class = UserProfileFilter
    search_fields = ('username',)
    ordering = 'create_datetime'  # 默认排序

    def get_user_details(self, request: Request, *args, **kwargs):
        """
        获取用户详情
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        userId = request.query_params.get('userId')
        if userId:
            instance = self.queryset.get(id=userId)
            serializer = self.get_serializer(instance)
            data = serializer.data
            if hasattr(self, 'handle_logging'):
                self.handle_logging(request, instance=instance, *args, **kwargs)
        return SuccessResponse(data)



class WorkRoleModelViewSet(CustomModelViewSet):
    """
    角色管理 的CRUD视图
    """
    queryset = Comp_Role.objects.all()
    serializer_class = RoleSerializer
    create_serializer_class = RoleCreateUpdateSerializer
    update_serializer_class = RoleCreateUpdateSerializer
    filter_class = RoleFilter
    search_fields = ('roleName',)
    ordering = 'create_datetime'  # 默认排序
    export_field_data = ['角色序号', '角色名称', '角色权限', '角色排序', '数据范围', '角色状态', '创建者', '修改者', '备注']
    export_serializer_class = ExportRoleSerializer

class WorkDeptModelViewSet(CustomModelViewSet):
    """
    部门管理 的CRUD视图
    """
    queryset = Comp_Dept.objects.all()
    serializer_class = WorkDeptSerializer
    create_serializer_class = WorkDeptCreateUpdateSerializer
    update_serializer_class = WorkDeptCreateUpdateSerializer
    filter_class = DeptFilter
    search_fields = ('deptName',)
    ordering = 'create_datetime'  # 默认排序

    def exclude_list(self, request: Request, *args, **kwargs):
        """
        过滤剔除同级部门
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        dept_queryset = Comp_Dept.objects.filter(id=kwargs.get('pk')).first()
        parentId = dept_queryset.parentId if dept_queryset else ''
        queryset = self.queryset.exclude(parentId=parentId).order_by('orderNum')
        if hasattr(self, 'handle_logging'):
            self.handle_logging(request, *args, **kwargs)
        serializer = self.get_serializer(queryset, many=True)
        return SuccessResponse(serializer.data)

    def tree_select_list(self, request: Request, *args, **kwargs):
        """
        递归获取部门树
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.filter_queryset(self.get_queryset())
        if hasattr(self, 'handle_logging'):
            self.handle_logging(request, *args, **kwargs)
        serializer = WorkDeptTreeSerializer(queryset, many=True)
        return SuccessResponse(serializer.data)

    def role_dept_tree_select(self, request: Request, *args, **kwargs):
        """
        根据角色ID查询部门树结构
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        dept_queryset = Comp_Dept.objects.filter(role__id=kwargs.get('pk')).values_list('id', flat=True)
        queryset = self.filter_queryset(self.get_queryset())
        if hasattr(self, 'handle_logging'):
            self.handle_logging(request, *args, **kwargs)
        serializer = WorkDeptTreeSerializer(queryset, many=True)
        return SuccessResponse({
            'depts': serializer.data,
            'checkedKeys': dept_queryset
        })




class WorkModelViewSet(CustomModelViewSet):
    """
    客户中心 的CRUD视图
    """
    queryset = All_Kq_Infos.objects.all()
    serializer_class = WorkSerializer  # 序列化器
    create_serializer_class = WorkCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = WorkCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = WorkFilter  # 过滤器
    # extra_filter_backends = [DataLevelPermissionsFilter]  # 数据权限类，不需要可注释掉
    # update_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    # destroy_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    # create_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    search_fields = ('parCompName',)  # 搜索
    ordering = ['-parCompName', '-empNum']  # 默认排序
    # 导出
    export_field_data = ['编号', '公司名称', '公司法人', '注册资本', '实缴资本', '成立日期', '经营状态', '省份', '地市',
                         '区县', '街道/乡镇', '公司类型', '所属行业', '曾用名', '参保人数', '联系电话', '其他电话', '地址', '网址',
                         '邮箱', '经营范围',
                         ]  # 导出
    export_serializer_class = ExportWorkSerializer  # 导出序列化器
    # 导入客户库
    import_field_data = {'compName': '项目名称', 'compOwner': '公司法人', 'regCap': '注册资本', 'realCap': '实缴资本',
                         'foundDay': '成立日期', 'opStatus': '经营状态', 'province': '省份', 'city': '地市', 'district': '区县',
                         'compType': '公司类型', 'industry': '所属行业', 'oldName': '曾用名', 'empNum': '参保人数', 'phone': '联系电话',
                         'otherPhone': '其他电话', 'address': '地址', 'url': '网址', 'email': '邮箱', 'businessScope': '经营范围'
                         }
    import_serializer_class = ExportWorkSerializer

    def update_kq_info_status(self, request: Request, *args, **kwargs):
        """
        更新数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        instance = self.queryset.get(id=request.data.get('id'))
        serializer = self.get_serializer(instance)
        instance.isMyCustomer = request.data.get('isMyCustomer')
        # instance.infoStatus = request.data.get('infoStatus')
        instance.save()
        return SuccessResponse(serializer.data)

    def batch_update_kq_info_status(self, request: Request, *args, **kwargs):
        """
        批量更新数据 batchUpdateKqInfo
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        for item in request.data:
            instance = self.queryset.get(id=item.get('id'))
            instance.isMyCustomer = item.get('isMyCustomer')
            # instance.infoStatus = item.get('infoStatus')
            instance.save()
        return SuccessResponse({'msg': '批量更新成功！'})

    def batch_delete_kq_info(self, request: Request, *args, **kwargs):
        """
        批量更新数据 batchDeleteKqInfo
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        for item in request.data:
            instance = self.queryset.get(id=item)
            instance.isDeleted = 1
            instance.save()
        return SuccessResponse({'msg': '批量删除成功！'})

    def recover_kq_info(self, request: Request):
        instance = self.queryset.get(id=request.data)
        instance.isDeleted = 0
        instance.save()
        return SuccessResponse({'msg': '数据恢复成功！'})


class KqOrdersModelViewSet(CustomModelViewSet):
    """
        订单中心 的CRUD视图
        """
    queryset = All_Kq_Orders.objects.all()
    serializer_class = OrderSerializer  # 序列化器
    create_serializer_class = OrderCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = OrderCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = OrderFilter  # 过滤器
    # extra_filter_backends = [DataLevelPermissionsFilter]  # 数据权限类，不需要可注释掉
    # update_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    # destroy_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    # create_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    search_fields = ('compName',)  # 搜索
    ordering = ['-orderDate']  # 默认排序
    # 导出
    export_field_data = ['编号', '订单ID', '公司名称', '项目名称', '成交产品列表', '成交额', '成交时间', '订单种类', '业务员',
                         '是否在职', '性别', '职位', '所属大区', '所属部门'
                         ]  # 导出
    export_serializer_class = ExportOrderSerializer  # 导出序列化器
    # 导入我的订单
    import_field_data = {'orderId': '订单ID', 'compName': '公司名称', 'projectName': '项目名称', 'products': '成交产品列表',
                         'dealNum': '成交额', 'orderDate': '成交时间', 'orderType': '订单种类', 'collaborator': '业务员',
                         'compType': '是否在职', 'sex': '性别', 'position': '职位', 'maxDepartment': '所属大区',
                         'department': '所属部门'
                         }
    import_serializer_class = ExportOrderSerializer


class KqExtendInfoModelViewSet(CustomModelViewSet):
    """
        订单中心 的CRUD视图
        """
    queryset = Kq_Extend_infos.objects.all()
    serializer_class = KqExtendInfoSerializer  # 序列化器
    create_serializer_class = KqExtendInfoCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = KqExtendInfoCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = KqExtendInfoFilter  # 过滤器
    search_fields = ('kqId',)  # 搜索
    ordering = ['kqId', ]  # 默认排序

    def get_extend_info_by_id(self, request: Request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        data_count = queryset.filter(kqId=kwargs.get("pk")).count()
        if data_count > 0:
            instance = self.queryset.get(kqId=kwargs.get("pk"))
            serializer = self.get_serializer(instance)
            return SuccessResponse(
                data={"obj": serializer.data,
                      "isExist": 1
                      })
        return SuccessResponse(data={"obj": {}, "isExist": 0})


class KqMaintainModelViewSet(CustomModelViewSet):
    """
        维护 的CRUD视图
        """
    queryset = Kq_Maintain_infos.objects.all()
    serializer_class = KqMaintainSerializer  # 序列化器
    create_serializer_class = KqMaintainCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = KqMaintainCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = KqMaintainInfoFilter  # 过滤器
    # extra_filter_backends = [DataLevelPermissionsFilter]  # 数据权限类，不需要可注释掉
    # update_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    # destroy_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    # create_extra_permission_classes = (CommonPermission,)  # 判断用户是否有这条数据的权限
    search_fields = ('compName',)  # 搜索
    ordering = ['-create_datetime']  # 默认排序
    # 导出
    export_field_data = ['拜访时间', '公司名称', '拜访负责人', '负责人职位', '电话/手机', '公司主营业务', '公司年用泵量', '公司常用泵类型', '拜访详情']  # 导出
    export_serializer_class = ExportMaintainSerializer  # 导出序列化器


class KqPriceInfoModelViewSet(CustomModelViewSet):
    """
        订单中心 的CRUD视图
        """
    queryset = Kq_Price_infos.objects.all()
    serializer_class = KqPriceSerializer  # 序列化器
    create_serializer_class = KqPriceCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = KqPriceCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = KqPriceInfoFilter  # 过滤器KqMaintainModelViewSet
    search_fields = ('compName', 'projectName')  # 搜索
    ordering = ['-create_datetime', ]  # 默认排序


class KqPumpsModelViewSet(CustomModelViewSet):
    """
        订单中心 的CRUD视图
        """
    queryset = Kq_All_Pumps.objects.all()
    serializer_class = KqPumpsSerializer  # 序列化器
    create_serializer_class = KqPumpsCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = KqPumpsCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = KqPumpsFilter  # 过滤器
    search_fields = ('type', 'flow', 'height', 'power', 'rev', 'calibre', 'kind', 'compType',)  # 搜索
    ordering = ['kind', 'flow', 'power']  # 默认排序
    # 导出
    export_field_data = ['ID', '水泵类型', '型号', '流量', '扬程', '功率', '转速', '口径', '公司', '描述']  # 导出
    export_serializer_class = ExportKqPumpsSerializer  # 导出序列化器


class KqAllProjectsModelViewSet(CustomModelViewSet):
    """
        项目 的CRUD视图
        """
    queryset = Kq_All_Projects.objects.all()
    serializer_class = KqAllProjectsSerializer  # 序列化器
    create_serializer_class = KqAllProjectCreateUpdateSerializer  # 创建/更新时的列化器
    update_serializer_class = KqAllProjectCreateUpdateSerializer  # 创建/更新时的列化器
    filter_class = KqAllProjectsFilter
    search_fields = ('projectName', 'buyer', 'seller')  # 搜索
    ordering = ['-releaseDate', ]  # 默认排序
